﻿// -----------------------------------------------------------------------
// <copyright file="FormConnector.cs" company="Abyssalsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Gui.BaseForm
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;

    /// <summary>
    /// Used to move all forms together
    /// </summary>
    public class FormConnector
    {
        /// <summary>The main form</summary>
        private Form mMainForm;

        /// <summary>Represents a list with all the opened forms</summary>
        private List<Form> mConnectedForms = new List<Form>();

        /// <summary>The location of the main form</summary>
        private Point mMainLocation;

        /// <summary>
        /// Initializes a new instance of the FormConnector class.
        /// </summary>
        /// <param name="mainForm">Connect and subscribe to LocationChanged event of the given form</param>
        public FormConnector(Form mainForm)
        {
            if (mainForm != null)
            {
                this.mMainForm = mainForm;
                this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
                this.mMainForm.LocationChanged += new EventHandler(this.MainForm_LocationChanged);
            }
        }

        /// <summary>
        /// Connect to form
        /// </summary>
        /// <param name="form">The form to connect to</param>
        public void ConnectForm(Form form)
        {
            if (!this.mConnectedForms.Contains(form))
            {
                this.mConnectedForms.Add(form);
            }
        }

        /// <summary>
        /// Release resources used and unsubscribe events
        /// </summary>
        public void Release()
        {
            if (this.mMainForm != null)
            {
                this.mMainForm.LocationChanged -= new EventHandler(this.MainForm_LocationChanged);
            }
        }

        /// <summary>
        /// Occurs when the form location is changed, and moves the forms together
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Event args.</param>
        private void MainForm_LocationChanged(object sender, EventArgs e)
        {
            Point relativeChange = new Point(this.mMainForm.Location.X - this.mMainLocation.X, this.mMainForm.Location.Y - this.mMainLocation.Y);
            foreach (Form form in this.mConnectedForms)
            {
                form.Location = new Point(form.Location.X + relativeChange.X, form.Location.Y + relativeChange.Y);
            }

            this.mMainLocation = new Point(this.mMainForm.Location.X, this.mMainForm.Location.Y);
        }
    }
}
